package com.github.cooingandwooing.pipeline;

import java.util.List;

import com.github.cooingandwooing.bo.HyCaseBusiness;
import com.github.cooingandwooing.model.CaseInfoDto;
import com.github.cooingandwooing.service.HyCaseBusinessService;
import com.github.cooingandwooing.utils.Converter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 〈〉
 *
 * @author Administrator
 * @create 2022/4/28
 * @since 1.0.0
 */
@Slf4j
@Component
public class HuayuPipeline implements Pipeline {

    @Autowired
    private HyCaseBusinessService hyCaseBusinessService;

    @Override
    public void process(ResultItems resultItems, Task task) {
        if (resultItems != null && resultItems.getAll() != null) {
            List<CaseInfoDto> caseInfoDtoList = resultItems.get("caseInfoDtoList");
            if (caseInfoDtoList != null && caseInfoDtoList.size() > 0) {
                String cBhAj = resultItems.get("cBhAj");
                String nAjlb = resultItems.get("nAjlb");

                HyCaseBusiness hyCaseBusiness = Converter.caseInfoConvert2(caseInfoDtoList);
                if (StringUtils.isNotBlank(cBhAj)) {
                    hyCaseBusiness.setAjbh(cBhAj);
                }
                if (StringUtils.isNotBlank(nAjlb)) {
                    hyCaseBusiness.setXajlbId(Integer.valueOf(nAjlb));
                }
                hyCaseBusinessService.saveOrUpdate(hyCaseBusiness);
                log.info("插入案件信息到数据库，案件编号{}", hyCaseBusiness.getAjbh());
            }
            else {
                log.error("案件信息获取为空，请查看链接{}", resultItems.getRequest().getUrl());
            }
        }else {
            log.info("本次 page 下载结果，不是案件详情页");
        }
    }
}